package com.wzy.sort8;

import java.util.Arrays;

/**
 * @author wzy
 * @Date: 2022/1/30 14:20
 * @Description: 归并排序 ： 合并两个有序数组的过程
 */
public class Merge {
    public static void main(String[] args) {
        int[] nums = {5, 1, 8, 2, 6, 7, 3, 4};
        mergeSort(nums, 0, nums.length - 1);
        System.out.println(Arrays.toString(nums));
    }

    public static void mergeSort(int[] nums, int l, int r) {
        if (l == r) {
            return;
        }
        int middle = l + (r - l) / 2;
        // 递归使左右都有序
        mergeSort(nums, l, middle);
        mergeSort(nums, middle + 1, r);
        // 两个有序数组合并
        merge(nums, l, middle, r);
    }

    public static void merge(int[] nums, int l, int middle, int r) {
        int[] help = new int[r - l + 1];
        int indexR = middle + 1, index = 0,pos = l;
        while (l <= middle && indexR <= r) {
            if (nums[l] < nums[indexR]) {
                help[index++] = nums[l];
                l++;
            } else {
                help[index++] = nums[indexR];
                indexR++;
            }
        }
        // 跳出上面的循环则至少有一边数组遍历完成
        while (l <= middle) {
            help[index++] = nums[l++];

        }
        while (indexR <= r) {
            help[index++] = nums[indexR++];
        }
        // 在该区间有序
        for (int i = 0; i < help.length; i++) {
            nums[pos + i] = help[i];
        }
    }

    public static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
